<!-- src/views/stocktaking/task/AddTask.vue -->
<script setup>
import { ref, reactive, watch } from 'vue'
import { getTaskListApi } from '@/api/warehousingEntryUp.js'
import { ElMessage } from 'element-plus'

// 定义组件属性
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

// 定义事件发射
const emit = defineEmits(['update:visible', 'confirm'])

// 表单数据
const form = reactive({
  taskName: '',
  cronExpression: '',
  category: null,
  targetId: null,
  targetName: '',
  empId: null,
  isEnable: 1
})

// 表单引用
const formRef = ref()

// 目标选项列表
const targetOptions = ref([])

// 加载状态
const loading = ref(false)

// 盘点类型选项
const categoryOptions = [
  { label: '仓库盘点', value: 1 },
  { label: '库区盘点', value: 2 },
  { label: '库位盘点', value: 3 }
]

// Cron表达式生成相关数据
const cronFrequency = ref('')
const cronOptions = [
  { label: '每5秒', value: '0/5 * * * * ?' },
  { label: '每分钟', value: '0 * * * * ?' },
  { label: '每5分钟', value: '0 0/5 * * * ?' },
  { label: '每10分钟', value: '0 0/10 * * * ?' },
  { label: '每小时', value: '0 0 * * * ?' },
  { label: '每天凌晨1点', value: '0 0 1 * * ?' },
  { label: '每周一凌晨1点', value: '0 0 1 ? * 2' },
  { label: '每月1号凌晨1点', value: '0 0 1 1 * ?' }
]

// 表单校验规则
const rules = {
  taskName: [
    { required: true, message: '请输入任务名称', trigger: 'blur' }
  ],
  cronExpression: [
    { required: true, message: '请选择执行时间表达式', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择盘点类型', trigger: 'change' }
  ],
  targetId: [
    { required: true, message: '请选择目标', trigger: 'change' }
  ]
}

// 监听盘点类型变化
watch(() => form.category, async (newVal) => {
  if (newVal) {
    try {
      loading.value = true
      const res = await getTaskListApi(newVal)
      targetOptions.value = res.data.map(item => ({
        label: item.name,
        value: item.id
      }))
      // 清空之前选择的目标
      form.targetId = null
      form.targetName = ''
    } catch (error) {
      ElMessage.error('获取目标列表失败')
    } finally {
      loading.value = false
    }
  } else {
    targetOptions.value = []
    form.targetId = null
    form.targetName = ''
  }
})

// 监听目标选择变化
watch(() => form.targetId, (newVal) => {
  if (newVal) {
    const selectedTarget = targetOptions.value.find(item => item.value === newVal)
    if (selectedTarget) {
      form.targetName = selectedTarget.label
    }
  } else {
    form.targetName = ''
  }
})

// 监听cron表达式选择变化
watch(cronFrequency, (newVal) => {
  form.cronExpression = newVal
})

// 重置表单
const resetForm = () => {
  form.taskName = ''
  form.cronExpression = ''
  form.category = null
  form.targetId = null
  form.targetName = ''
  form.empId = null
  form.isEnable = 1
  targetOptions.value = []
  cronFrequency.value = ''
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  resetForm()
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 发送数据给父组件
      emit('confirm', { ...form })
    } else {
      ElMessage.warning('请填写完整信息')
      return false
    }
  })
}

// 暴露方法给父组件调用
defineExpose({
  resetForm
})
</script>

<template>
  <el-dialog
    title="添加盘点任务"
    :model-value="visible"
    @close="handleClose"
    width="600px"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="padding-right: 20px"
    >
      <el-form-item label="任务名称" prop="taskName" required>
        <el-input 
          v-model="form.taskName" 
          placeholder="请输入任务名称" 
        />
      </el-form-item>
      
      <el-form-item label="执行频率" prop="cronExpression" required>
        <el-select 
          v-model="cronFrequency" 
          placeholder="请选择执行频率"
          style="width: 100%"
        >
          <el-option
            v-for="item in cronOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="Cron表达式" prop="cronExpression" required>
        <el-input 
          v-model="form.cronExpression" 
          placeholder="Cron表达式会根据执行频率自动生成"
          readonly
        />
      </el-form-item>
      
      <el-form-item label="盘点类型" prop="category" required>
        <el-select 
          v-model="form.category" 
          placeholder="请选择盘点类型"
          style="width: 100%"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="目标" prop="targetId" required>
        <el-select 
          v-model="form.targetId" 
          placeholder="请选择目标"
          :loading="loading"
          style="width: 100%"
        >
          <el-option
            v-for="item in targetOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>